/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Simulation.Services.Common;

import Simulation.Messages.DisMessage;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author aking2
 */
public class DisMessageRelayer extends Thread {
    
    public DisMessageRelayer (ServiceComms to, String inRcvAddress, int inRcvPort) {
    
        rcvAddress = inRcvAddress;
        rcvPort = inRcvPort;
        destinationCommsSystem = to;
                 
        try {
            rcvDatagramSocket = new MulticastSocket(rcvPort);
            rcvDatagramSocket.setBroadcast(true);
            localDisNif = InetAddress.getByName(rcvAddress);
            nif = NetworkInterface.getByInetAddress(localDisNif);
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(DisMessageRelayer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SocketException ex) {
            Logger.getLogger(DisMessageRelayer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DisMessageRelayer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void AddMultiCastGroup( String address ) {
        InetSocketAddress isa = new InetSocketAddress(address, rcvPort);
        try {
            rcvDatagramSocket.joinGroup(isa, nif);
        } catch (IOException ex) {
            Logger.getLogger(DisMessageRelayer.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }
    
    @Override
    public void run() {        
        while (true) {
            try {
                rcvDatagramSocket.receive(rcvPacket);
                destinationCommsSystem.SendMessage(new DisMessage(rcvPacket.getData()));                
            } catch (IOException ex) {
                Logger.getLogger(DisMessageRelayer.class.getName()).log(Level.SEVERE, null, ex);
            }            
        }
    }                

    private ServiceComms destinationCommsSystem;
    private MulticastSocket rcvDatagramSocket;      
    private DatagramPacket rcvPacket;
    private InetAddress localDisNif;
    private NetworkInterface nif;
    private String rcvAddress;
    private int rcvPort;
    
}
